package com.example.mychat;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.mychat.Adapter.MsgAdapter;
import com.example.mychat.Bean.Msg;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {
    private ListView chatlv;
    private TextView chattxt;
    private EditText sendedit;
    private Button sendbtn;
    int sendid,receiveid;
    String receivename;
    List<Msg> msgList=new ArrayList<>();
    MsgAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_char);
        initData();
        initView();
        setListener();
    }

    private void initData() {//获取初始化数据的方法
        SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
        sendid=sp.getInt("myid",-1);
        receiveid=sp.getInt("friendid",-1);
        receivename=sp.getString("friendname","");
        for (Msg m: LitePal.findAll(Msg.class)){
            boolean a=sendid==m.getSend_id()&&receiveid==m.getReceive_id();
            boolean b=sendid==m.getReceive_id()&&receiveid==m.getReceive_id();
            if(a||b){
                msgList.add(m);
            }
        }
    }
    private void setListener() {
        sendbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=sendedit.getText().toString().trim();
                Msg m=new Msg(0,sendid,receiveid,content,new Date());
                m.save();
                msgList.add(m);
                adapter.notifyDataSetChanged();
                sendedit.setText("");
            }
        });
    }

    private void initView() {
        chatlv=findViewById(R.id.chatlv);
        chattxt=findViewById(R.id.chattxt);
        sendbtn=findViewById(R.id.sendbtn);
        sendedit=findViewById(R.id.sendedit);
        chattxt.setText("正在与"+receivename+"聊天中");
        adapter=new MsgAdapter(ChatActivity.this,
                R.layout.msg_item,msgList);
        chatlv.setAdapter(adapter);
    }
}
